'use strict';
const uniID = require('uni-id')
exports.main = async (event, context) => {
	console.log(event)
	const payload = await uniID.checkToken(event.uniIdToken)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		const res = await db.collection('orders').aggregate()
			.match({
				user_id: payload.uid,
				service_location: event.service_location
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$user_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						user_mobile: '$mobile'
					})
					.done(),
				as: 'user'
			})
			.lookup({
				from: 'uni-id-users',
				let: {
					userId: '$paramedic_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$userId'])))
					.project({
						_id: 0,
						paramedic_mobile: '$mobile',
						paramedic_name:'$paramedic_profile.name',
						paramedic_avatar:'$paramedic_profile.avatar'
					})
					.done(),
				as: 'paramedic'
			})
			.lookup({
				from: 'hospitals',
				let: {
					hospitalId: '$hospital_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$hospitalId'])))
					.project({
						_id: 0,
						hospital_name: '$name',
						hospital_logo: '$logo'
					})
					.done(),
				as: 'hospital'
			})
			.lookup({
				from: 'services',
				let: {
					serviceId: '$service_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$_id', '$$serviceId'])))
					.project({
						_id: 0,
						service_title: '$title'
					})
					.done(),
				as: 'service'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), $.arrayElemAt(['$paramedic', 0]),$.arrayElemAt(['$hospital', 0]),
					$.arrayElemAt(['$service', 0]), '$$ROOT'
				])
			})
			.project({
				user: 0,
				hospital: 0,
				service: 0,
				paramedic: 0
			})
			.end()
	
		return res
	}

